package com.ygswglxt.salary.controller;

import com.ygswglxt.salary.entity.SalaryRecord;
import com.ygswglxt.salary.service.SalaryService;
import com.ygswglxt.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/salary")
public class SalaryController {
    
    @Autowired
    private SalaryService salaryService;
    
    @GetMapping("/my")
    public Result<List<SalaryRecord>> getMySalary(HttpServletRequest request) {
        Long userId = Long.parseLong(request.getHeader("userId"));
        return salaryService.getMySalary(userId);
    }
    
    @GetMapping("/all")
    public Result<List<SalaryRecord>> getAllSalary(HttpServletRequest request) {
        String role = request.getHeader("role");
        if (!"HR".equals(role)) {
            return Result.error(403, "无权限访问");
        }
        return salaryService.getAllSalary();
    }
    
    @GetMapping("/team")
    public Result<List<SalaryRecord>> getTeamSalary(HttpServletRequest request) {
        String role = request.getHeader("role");
        if (!"MANAGER".equals(role)) {
            return Result.error(403, "无权限访问");
        }
        Long managerId = Long.parseLong(request.getHeader("userId"));
        // 简化处理：返回所有薪资记录（实际应该根据组织架构查询下属）
        return salaryService.getTeamSalary(managerId);
    }
    
    @PostMapping("/create")
    public Result<String> createSalary(@RequestBody SalaryRecord salaryRecord, HttpServletRequest request) {
        String role = request.getHeader("role");
        if (!"HR".equals(role)) {
            return Result.error(403, "无权限访问");
        }
        return salaryService.createSalary(salaryRecord);
    }
    
    @PutMapping("/update/{id}")
    public Result<String> updateSalary(@PathVariable Long id, @RequestBody SalaryRecord salaryRecord, HttpServletRequest request) {
        String role = request.getHeader("role");
        if (!"HR".equals(role)) {
            return Result.error(403, "无权限访问");
        }
        return salaryService.updateSalary(id, salaryRecord);
    }
    
    // 导出薪资记录
    @GetMapping("/export")
    public void exportSalaryRecords(
            @RequestParam(required = false) String month,
            HttpServletRequest request,
            HttpServletResponse response) {
        try {
            String userIdStr = request.getHeader("userId");
            String role = request.getHeader("role");
            Long userId = null;
            
            // 只有员工查看自己的记录，HR和经理可以查看所有
            if (!"HR".equals(role) && !"MANAGER".equals(role)) {
                userId = Long.parseLong(userIdStr);
            }
            
            salaryService.exportSalaryRecords(response, userId, month);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
        }
    }
}

